# 帧处理工具
import cv2
import base64
import numpy as np
from typing import Tuple, Optional


class FrameUtils:
    """帧处理工具类"""

    @staticmethod
    def resize_frame(frame: np.ndarray, width: int = None, height: int = None) -> np.ndarray:
        """
        调整帧大小
        Args:
            frame: 输入帧
            width: 目标宽度
            height: 目标高度
        Returns:
            调整后的帧
        """
        h, w = frame.shape[:2]

        if width is None and height is None:
            return frame

        if width is None:
            width = int(w * height / h)
        elif height is None:
            height = int(h * width / w)

        return cv2.resize(frame, (width, height))

    @staticmethod
    def frame_to_base64(frame: np.ndarray, format: str = '.jpg') -> str:
        """
        将帧转换为base64字符串
        Args:
            frame: 输入帧
            format: 图片格式
        Returns:
            base64编码的字符串
        """
        # 压缩图片以减少数据量
        encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 85]
        _, buffer = cv2.imencode(format, frame, encode_param)

        # 转换为base64
        frame_base64 = base64.b64encode(buffer).decode('utf-8')
        return f"data:image/jpeg;base64,{frame_base64}"

    @staticmethod
    def calculate_fps(frame_count: int, start_time: float, current_time: float) -> float:
        """
        计算FPS
        Args:
            frame_count: 帧计数
            start_time: 开始时间
            current_time: 当前时间
        Returns:
            FPS值
        """
        elapsed_time = current_time - start_time
        if elapsed_time == 0:
            return 0
        return frame_count / elapsed_time

    @staticmethod
    def validate_frame(frame: np.ndarray) -> bool:
        """
        验证帧是否有效
        Args:
            frame: 输入帧
        Returns:
            是否有效
        """
        return frame is not None and frame.size > 0
